package com.ztman.rxjava.view.activity;

import android.content.Intent;
import android.support.v4.util.ArrayMap;
import android.view.View;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.orhanobut.logger.Logger;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.RequestBody;
import com.ztman.rxjava.R;
import com.ztman.rxjava.model.baseEntity.BaseResponse;
import com.ztman.rxjava.model.baseEntity.BaseRxBusEvent;
import com.ztman.rxjava.model.entityExtends.upload.UoloadFileMulti;
import com.ztman.rxjava.model.entityExtends.upload.UploadFile;
import com.ztman.rxjava.model.entityExtends.upload.UploadModelIml;
import com.ztman.rxjava.mvp.presenter.ActivityPresenter;
import com.ztman.rxjava.mvp.viewProxy.UploadFileActivityProxy;
import com.ztman.rxjava.server.retrofit.OnNetRequestListener;
import com.ztman.rxjava.utils.ToastPop;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by YJH on 2017/11/30.
 * 功能：测试上传图片的 activity
 * 图库git地址：https://github.com/LuckSiege/PictureSelector
 */
public class UploadFileActivity extends ActivityPresenter<UploadFileActivityProxy> implements View.OnClickListener {

    private List<LocalMedia> selectList = new ArrayList<>();
    private UploadModelIml mUploadModelIml;

    @Override
    protected Class<UploadFileActivityProxy> getPresenterClass() {
        return UploadFileActivityProxy.class;
    }

    @Override
    protected void initData() {
        mUploadModelIml = new UploadModelIml();
    }

    int[] ids = {R.id.tWeather, R.id.tWeatherUpload};

    @Override
    protected void initView() {
        atyPresenter.setOnClickListener(this, ids);
    }

    @Override
    protected void receiveRxBuxCommanders(BaseRxBusEvent baseRxBusEvent) {

    }


    @Override
    public void onClick(View v) {
        if (ids[0] == v.getId()) {
            openMulti();

        } else if (ids[1] == v.getId()) {
            upload();
//            uploadMulti();
        }

    }


    private void openMulti() {
        // 进入相册 以下是例子：用不到的api可以不写
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofAll())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
//                .theme()//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                .maxSelectNum(3)// 最大图片选择数量 int
                .minSelectNum(1)// 最小选择数量 int
                .imageSpanCount(4)// 每行显示个数 int
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片 true or false
                .previewVideo(true)// 是否可预览视频 true or false
                .enablePreviewAudio(true) // 是否可播放音频 true or false
                .isCamera(true)// 是否显示拍照按钮 true or false
                .imageFormat(PictureMimeType.JPEG)// 拍照保存图片格式后缀,默认jpeg
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                .enableCrop(false)// 是否裁剪 true or false
                .compress(true)// 是否压缩 true or false
//                .glideOverride()// int glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
//                .withAspectRatio()// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
//                .hideBottomControls()// 是否显示uCrop工具栏，默认不显示 true or false
//                .isGif()// 是否显示gif图片 true or false
//                .compressSavePath("/CustomPath")//压缩图片保存地址
                .freeStyleCropEnabled(false)// 裁剪框是否可拖拽 true or false
                .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
//                .showCropGrid()// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
//                .openClickSound()// 是否开启点击声音 true or false
                .selectionMedia(selectList)// 是否传入已选图片 List<LocalMedia> list
                .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                .cropCompressQuality(90)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
//                .cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效 int
//                .rotateEnabled() // 裁剪是否可旋转图片 true or false
//                .scaleEnabled()// 裁剪是否可放大缩小图片 true or false
//                .videoQuality()// 视频录制质量 0 or 1 int
//                .videoMaxSecond(15)// 显示多少秒以内的视频or音频也可适用 int
//                .videoMinSecond(10)// 显示多少秒以内的视频or音频也可适用 int
//                .recordVideoSecond()//视频秒数录制 默认60s int
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    private void upload() {
        Logger.e("UploadFileActivity-上传文件地址--->>" + selectList.get(0).getCompressPath());
        File file = new File(selectList.get(0).getCompressPath());
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
        mUploadModelIml.setUploadParams(requestBody, 2, new OnNetRequestListener<BaseResponse<UploadFile>>() {
            @Override
            public void onRequestStart() {
                ToastPop.showShort("上传文件请求开始..");
            }

            @Override
            public void onRequestFinish() {
                ToastPop.showShort("上传文件请求结束..");
            }

            @Override
            public void onRequestSuccess(BaseResponse<UploadFile> data) {
                ToastPop.showShort("上传文件请求成功..");
                atyPresenter.setPicShow("");
                atyPresenter.setPicShow("成功！" + data.data.getUrl());
            }

            @Override
            public void onRequestFailure(Throwable t) {
                ToastPop.showShort("上传文件请求错误..");
                Logger.e("UploadFileActivity-上传文件地址错误--->>" + t.toString());
            }
        });

    }

    private void uploadMulti() {
        Map<String, RequestBody> params = new ArrayMap<>();
        for (LocalMedia path : selectList) {
            Logger.e("UploadFileActivity-多文件上传地址--->>" + path.getCompressPath());
            File file = new File(path.getCompressPath());
            RequestBody rBody = RequestBody.create(MediaType.parse("image/jpg"), file);
            params.put("file", rBody);
        }

        mUploadModelIml.setUploadParams(params, 2, new OnNetRequestListener<BaseResponse<UoloadFileMulti>>() {
            @Override
            public void onRequestStart() {
                ToastPop.showShort("多文件上传请求开始..");
            }

            @Override
            public void onRequestFinish() {
                ToastPop.showShort("多文件上传请求结束..");
            }

            @Override
            public void onRequestSuccess(BaseResponse<UoloadFileMulti> data) {
                ToastPop.showShort("多文件上传请求成功..");
                atyPresenter.setPicShow("");
                atyPresenter.setPicShow("成功！" + data.data.getGroupId());
            }

            @Override
            public void onRequestFailure(Throwable t) {
                ToastPop.showShort("多文件上传请求错误..");
                Logger.e("UploadFileActivity-多文件上传地址错误--->>" + t.toString());
            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的

                    String lPath = "";
                    for (LocalMedia p : selectList) {
                        lPath = lPath + "\n" + p.getCompressPath();
                    }
                    atyPresenter.setPicShow(lPath);
                    break;
            }
        }
    }


}
